package com.ysd.lis.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.WkFile;
import com.ysd.lis.entity.WkFolder;
import com.ysd.lis.mapper.WkFileMapper;
import com.ysd.lis.mapper.WkFolderMapper;
import com.ysd.lis.request.WkFolderParam;
import com.ysd.lis.service.WkFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * cold_chain.t_user 服务实现类
 * </p>
 *
 * @author peng
 * @since 2024-03-04
 */
@Service
@Slf4j
public class WkFileServiceImpl extends ServiceImpl<WkFileMapper, WkFile> implements WkFileService {
    private static final int MAX_POST_SIZE = 600 * 1024 * 1024;
    @Value("${wkFilePath}")
    private String filePath;
    @Autowired
    WkFileMapper wkFileMapper;
    @Autowired
    WkFolderMapper wkFolderMapper;
    @Override
    public Result uploadFiles(MultipartFile file, HttpServletRequest request) throws IOException{
        String folderId = request.getParameter("folderId");
        String name = file.getOriginalFilename();
        if (file == null) {
            return Result.fail("文件不能为空") ;
        }
        // 文件限制10M
        long size = file.getSize();
        if (size > MAX_POST_SIZE) {
            return Result.fail("length exceeds limit of 10M") ;
        }

        String folder = filePath + "\\" + DateUtil.format(new Date(), "yyyyMM") + File.separator;
        if (!FileUtil.exist(folder)) {
            FileUtil.mkdir(folder);
        }
        String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddhhmmssSSS")) + type;
        String path = folder + fileName;
        System.out.println("@@@@@@@@@@@@@@" + path);

        WkFile wkFile = new WkFile();
        wkFile.setFolderId(folderId);
        wkFile.setName(name);
        wkFile.setDocPath(path);
        wkFile.setFileExten(name.substring(name.lastIndexOf(".") + 1));
        wkFile.setFileSize(String.valueOf(size));
        wkFileMapper.insert(wkFile);
        File files = new File(path);
        if (FileUtil.exist(files)) {
            return Result.fail("文件已存在") ;
        }
        File file1 = FileUtil.writeBytes(file.getBytes(), path);
        if (file1.length() < 0) {
            return Result.fail("文件上传失败");
        }
        return Result.succ(1, "上传成功", fileName);

    }

    @Override
    public Result findFolderAndFileList(WkFolderParam param) {
        List<WkFile> fList = new ArrayList<>();
        //先查询文件夹
        LambdaQueryWrapper<WkFolder> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(WkFolder::getDelFlag,0);
        queryWrapper1.eq(WkFolder::getPid,param.getFolderId());
        queryWrapper1.orderByAsc(WkFolder::getSeq);
        List<WkFolder> folderList = wkFolderMapper.selectList(queryWrapper1);

        for (WkFolder wkFolder :  folderList){
            WkFile wkFile = new WkFile();
            wkFile.setId(wkFolder.getId());
            wkFile.setName(wkFolder.getName());
            wkFile.setCode(wkFolder.getCode());
            wkFile.setFolderId(wkFolder.getPid());
            wkFile.setSeq(wkFolder.getSeq());
            wkFile.setFileExten("explorer");
            wkFile.setFileSize("1");
            wkFile.setShowType("文件夹");
            fList.add(wkFile);
        }

        //在查询文件
        LambdaQueryWrapper<WkFile> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WkFile::getDelFlag,0);
        queryWrapper.eq(WkFile::getFolderId,param.getFolderId());
        queryWrapper.orderByAsc(WkFile::getSeq);
        List<WkFile> fileList = wkFileMapper.selectList(queryWrapper);
        fList.addAll(fileList);
        return Result.succ(1, "查询成功", fList);
    }

    @Override
    public Result findFolderAndFileListByCode(WkFolderParam param) {
        List<WkFile> fList = new ArrayList<>();
        //先查询文件夹
        LambdaQueryWrapper<WkFolder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WkFolder::getDelFlag,0);
        wrapper.eq(WkFolder::getCode,param.getCode());

        List<WkFolder> folderList1 = wkFolderMapper.selectList(wrapper);
        if (CollectionUtils.isNotEmpty(folderList1)){

            String id = folderList1.get(0).getId();
            LambdaQueryWrapper<WkFolder> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(WkFolder::getDelFlag,0);
            queryWrapper1.eq(WkFolder::getPid,id);
            List<WkFolder> wkFolderList = wkFolderMapper.selectList(queryWrapper1);

            for (WkFolder wkFolder :  wkFolderList){
                WkFile wkFile = new WkFile();
                wkFile.setId(wkFolder.getId());
                wkFile.setName(wkFolder.getName());
                wkFile.setCode(wkFolder.getCode());
                wkFile.setFolderId(wkFolder.getPid());
                wkFile.setSeq(wkFolder.getSeq());
                wkFile.setFileExten("explorer");
                wkFile.setFileSize("1");
                wkFile.setShowType("文件夹");
                fList.add(wkFile);
            }

            //在查询文件
            LambdaQueryWrapper<WkFile> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WkFile::getDelFlag,0);
            queryWrapper.eq(WkFile::getFolderId,id);
            queryWrapper.orderByAsc(WkFile::getSeq);
            List<WkFile> fileList = wkFileMapper.selectList(queryWrapper);
            fList.addAll(fileList);
        }


        return Result.succ(1, "查询成功", fList);
    }

    @Override
    public Result deleteFile(WkFile wkFile) {
        File file = new File(wkFile.getDocPath());
        boolean deleteFile;
        if (file.exists()) {
             deleteFile = file.delete();
        }else{
            deleteFile = true;
        }
        if(deleteFile){
            int i = wkFileMapper.deleteById(wkFile.getId());
        }
        return Result.succ(1, "删除成功", "");
    }

    @Override
    public void downWkFile(String id, HttpServletResponse response) {
        try {
            WkFile wkFile = wkFileMapper.selectById(id);
            String url = wkFile.getDocPath();
            File file = new File(url);
            FileInputStream fileInputStream = new FileInputStream(file);
            long size = file.length();
            byte[] temp = new byte[(int) size];
            fileInputStream.read(temp, 0, (int) size);
            fileInputStream.close();
            byte[] data = temp;
            String type = url.substring(url.lastIndexOf(".") + 1);
            if ("pdf".equals(type)) {
                response.setContentType("application/pdf;charset=UTF-8");
            } else if ("doc".equals(type) || "docx".equals(type)) {
                response.setContentType("application/msword;charset=UTF-8");
            } else if ("xls".equals(type) || "xlsx".equals(type)) {
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            } else if ("txt".equals(type)) {
                response.setContentType("text/plain;charset=UTF-8");
            }
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(wkFile.getName(), "UTF-8"));
            OutputStream os = response.getOutputStream();
            os.write(data);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void viewWkFile(String id, HttpServletResponse response) {
        try {
            WkFile wkFile = wkFileMapper.selectById(id);
            String docPath = wkFile.getDocPath();
            BufferedInputStream in = FileUtil.getInputStream(docPath);
            String type = docPath.substring(docPath.lastIndexOf(".") + 1);
            if ("pdf".equals(type)) {
                response.setContentType("application/pdf;charset=UTF-8");
            } else if ("doc".equals(type) || "docx".equals(type)) {
                response.setContentType("application/msword;charset=UTF-8");
            } else if ("xls".equals(type) || "xlsx".equals(type)) {
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            } else if ("txt".equals(type)) {
                response.setContentType("text/plain;charset=UTF-8");
            } else {
                response.setContentType("image/jpeg");
            }
            response.setContentLength(in.available());
            OutputStream os = response.getOutputStream();
            IoUtil.copy(in, os, IoUtil.DEFAULT_BUFFER_SIZE);
            in.close();
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Result editFile(WkFile file) {
        int updateById = wkFileMapper.updateById(file);
        if(updateById>0){
            return Result.succ(1,"提交成功",file);
        }else {
            return Result.fail(400,"修改失败","");
        }
    }

    @Override
    public Result copyFile(WkFile file) throws IOException {



        String folder = filePath + "\\" + DateUtil.format(new Date(), "yyyyMM") + File.separator;
        if (!FileUtil.exist(folder)) {
            FileUtil.mkdir(folder);
        }
        String docPath = file.getDocPath();
        String type = docPath.substring(docPath.lastIndexOf("."));
        String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddhhmmssSSS")) + type;
        String path = folder + fileName;
        file.setDocPath(path);
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
             fis = new FileInputStream(new File(docPath));
             fos = new FileOutputStream(new File(path));
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
            }
            fos.close();
            fis.close();
            wkFileMapper.insert(file);
        }catch (IOException e){

            e.printStackTrace();
        }finally {
            fos.close();
            fis.close();
        }

        return Result.succ(1, "复制文件成功", file);
    }
}
